package com.shj.em.biz.sell.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.shj.em.aa.entity.User;
import com.shj.em.base.controller.BaseController;
import com.shj.em.base.support.ResMsg;
import com.shj.em.base.vo.PageVO;
import com.shj.em.biz.Constants;
import com.shj.em.biz.company.entity.Company;
import com.shj.em.biz.company.entity.Contact;
import com.shj.em.biz.sell.dto.QuotEditInitDTO;
import com.shj.em.biz.sell.dto.QuotSearchDTO;
import com.shj.em.biz.sell.dto.QuotSearchPageInitDTO;
import com.shj.em.biz.sell.entity.QuotItem;
import com.shj.em.biz.sell.entity.Quotation;
import com.shj.em.biz.sell.service.QuotItemService;
import com.shj.em.biz.sell.service.QuotationService;
import com.shj.em.biz.sys.entity.Cd;
import com.shj.em.biz.sys.service.CdService;
import com.shj.em.common.annotation.Log;
import com.shj.em.util.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * <p>
 * 报价信息 前端控制器
 * </p>
 *
 * @author Shen Huang Jian
 * @since 2018-07-07
 */
@RestController
@Slf4j
@RequestMapping("/sell/quot")
public class QuotationController extends BaseController<Quotation>{

    @Autowired
    QuotationService quotationService;

    @Autowired
    QuotItemService itemService;

    @GetMapping("/loadInitPageData")
    public QuotSearchPageInitDTO loadInitPageData(){
        boolean isManager = ShiroUtils.isManager();
        boolean isSuper = ShiroUtils.isSuperAdmin();
        //boolean isFinance = ShiroUtils.isFinancial();
        QuotSearchPageInitDTO initDTO = new QuotSearchPageInitDTO();

        List<Company> companyList = null;
        if(isManager || isSuper){
            companyList = companyService.getAllCustomers();
            List<User> sells = userService.getUsersByRoleId(Constants.ROLE_SELL);
            initDTO.setSells(sells);
            initDTO.setShowSells(true);
        }else{
            companyList = companyService.getCustomersBySellMan(ShiroUtils.getUserId());
            initDTO.setShowSells(false);
        }

        initDTO.setCustomers(companyList);

        List<Cd> units = cdService.queryCdsByType(CdService.CD_TYPE_UNIT);
        initDTO.setUnits(units);
        return initDTO;
    }

    @RequestMapping("/list")
    public PageVO<Quotation> list(@RequestBody QuotSearchDTO searchDTO){
        boolean isManager = ShiroUtils.isManager();
        boolean isSuper = ShiroUtils.isSuperAdmin();
        boolean isFinance = ShiroUtils.isFinancial();
        if(!isManager && !isSuper && !isFinance){
            searchDTO.setShowMyCustomer(true);
            searchDTO.setSellMan(ShiroUtils.getUserId());
        }else{
            searchDTO.setShowMyCustomer(false);
        }

        Page<Quotation> page = quotationService.queryQuotationPage(searchDTO);
        PageVO<Quotation> pageVO = new PageVO<>();
        pageVO.setTotal(page.getTotal());
        pageVO.setRows(page.getRecords());
        return pageVO;
    }

    @GetMapping("/initQuotation/{quotId}")
    public ResMsg<QuotEditInitDTO> initQuotation(@PathVariable("quotId") long quotId){
        boolean isEdit = quotId > -1L;
        QuotEditInitDTO initDTO = new QuotEditInitDTO();
        Quotation quotation = isEdit? quotationService.selectById(quotId) : new Quotation();

        if(isEdit){
            //获取报价中的产品
            List<QuotItem> items = itemService.queryQuotItemsByQuotId(quotId);
            initDTO.setItemList(items);

            if(quotation.getCustId() != null){
                List<Contact> contacts = contactService.findContactsByCompanyId(quotation.getCustId());
                initDTO.setContactList(contacts);
            }
        }else{
            Date now = new Date();
            quotation.setQuotDt(now);
            quotation.setQuotNo(quotationService.genQuotationNo(now));
        }
        initDTO.setQuot(quotation);
        return ResMsg.ok(initDTO);

    }

	@Log("创建报价信息")
	@PostMapping("/add")
	public ResMsg add(@RequestBody Quotation quotation){
        try{
            boolean isExist = quotationService.isQuotNoExist(quotation.getQuotNo(), null);
            if(isExist){
                return ResMsg.error("报价单号已存在。");
            }
            Quotation saved = quotationService.createQuotation(quotation);
            return ResMsg.ok("成功创建报价信息。", saved);
        }catch(Exception e){
            log.error("创建报价信息失败", e);
            return ResMsg.error("创建报价信息失败");
        }

	}

    @Log("更新报价信息")
	@PostMapping("/edit")
	public ResMsg edit(@RequestBody Quotation quotation){
        try{
            boolean isExist = quotationService.isQuotNoExist(quotation.getQuotNo(), quotation.getId());
            if(isExist){
                return ResMsg.error("报价单号已存在。");
            }
            quotationService.updateById(quotation);
            return ResMsg.ok("修改报价信息成功。");
        }catch(Exception e){
            log.error("更新报价信息失败", e);
            return ResMsg.error("更新报价信息失败");
        }
	}

    @PutMapping("/convert/{id}")
	public ResMsg convert(@PathVariable("id") Long quotId){
        Long id = quotationService.convert2Order(quotId);
        return ResMsg.ok(id);
    }


    @Log("批量删除报价")
	@DeleteMapping
	public ResMsg batchRemove(@RequestBody Long[] ids){
        quotationService.deleteBatchIds(Arrays.asList(ids));
		return ResMsg.ok();
	}

}

